package com.hehan.hhdemo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by hehan on 2018/11/28.
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ThreadDemo {

    @Test
    public void newCachedThreadPoolTest() {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        for (int i = 0; i < 10; i++) {

            final int index = i;

            try {
                    Thread.sleep(index * 1000);
                    } catch (InterruptedException e) {
                    e.printStackTrace();
                  }

            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(index+"==============================================================");
                }
            });
        }

    }




    @Test
    public void newScheduleThreadPoolTest() {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        scheduledThreadPool.schedule(new Runnable() {
            public void run() {
                System.out.println("delay 3 seconds");
            }
        }, 3, TimeUnit.SECONDS);
    }

    @Test
    public void newFixedThreadPoolTest() {
            ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
            for (int i = 0; i < 10; i++) {
                final int index = i;
                singleThreadExecutor.execute(new Runnable() {
                    public void run() {
                        try {
                            System.out.println(index);
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }




}
